/*
 * @Author: xishanxu
 * @LastEditors  : xisuanxu
 * @LastEditTime : 2019-12-22 17:20:19
 */
import { Effect } from 'dva';
import { Reducer } from 'redux';

import { getUserInfo } from '@/services/user';

export interface CurrentUser {
  id?: string;
  name?: string;
  phone?: string;
  image?: string;
  sex?: number;
  email?: string | null;
  phone_verified_at?: string | null;
  email_verified_at?: string | null;
  created_at?: string | null;
  updated_at?: string | null;
  deleted_at?: string | null;
  currentAuthority?: string | string[]; // 以后user可能有多个角色 [admin, teacher]
  notifyCount?: any;
  unreadCount?: any;
}

export interface UserModelState {
  currentUser?: CurrentUser;
}

export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    *fetchCurrent(_, { call, put }) {
      // //  window.console.log((112, 998);
      const response = yield call(getUserInfo);
      yield put({
        type: 'saveCurrentUser',
        payload: response.data,
      });
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      // //  window.console.log((action, 998);
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default UserModel;
